<template>
  <e-container :loading="loading">
    <a-space :size="24">
      <a-button size="small" @click="() => router.push({ name: 'Price', params: { id: applyId } })">
        <template #icon>
          <e-icon type="Aright" />
        </template>
      </a-button>
      <e-title title="Edit Price Application" />
    </a-space>
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiDataBase" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Subject" name="theme">
              <a-input v-model:value="apiDataBase.theme" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Language Pair" name="langPairID">
              <a-spin :spinning="languagePairLoading">
                <a-select
                  v-model:value="apiDataBase.langPairID"
                  :disabled="!isEditing"
                  mode="multiple"
                  :get-popup-container="triggerNode => triggerNode.parentNode"
                  option-filter-prop="label">
                  <a-select-option v-for="item in languagePairs" :key="item.langPairID" :label="item.langPairName">
                    {{ item.langPairName }}
                  </a-select-option>
                </a-select>
              </a-spin>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="BUM" name="bumid">
              <a-spin :spinning="bumSelectLoading">
                <a-select
                  v-model:value="apiDataBase.bumid"
                  :get-popup-container="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="item in bumCandidates" :key="item.empID">
                    {{ item.empName }}
                  </a-select-option>
                </a-select>
              </a-spin>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Attachment" name="fileName">
              <a-input :value="fileName" :readonly="true">
                <template #addonAfter>
                  <input v-show="false" ref="uploadInput" type="file" @change="uploadFileChange" />
                  <span style="color: #a9b5c9; cursor: pointer" @click="uploadInput.click()">
                    <e-icon type="upload" style="margin-right: 6px" />Upload
                  </span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider />
      <a-spin :spinning="backgroundInfoLoading">
        <a-form ref="backgroundFormInstance" :model="apiDataBackground" layout="vertical" :rules="rules">
          <a-row :gutter="gutter">
            <a-col :span="12">
              <a-form-item label="Competitors Information" name="rivalID">
                <a-select
                  v-model:value="apiDataBackground.rivalID"
                  :get-popup-container="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="item in dict.rivals" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="Competitors Type" name="rivalLevelID">
                <a-select
                  v-model:value="apiDataBackground.rivalLevelID"
                  :get-popup-container="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="item in dict.rivalLevels" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="gutter">
            <a-col :span="12">
              <a-form-item label="Client Value" name="valueID">
                <a-select
                  v-model:value="apiDataBackground.valueID"
                  :get-popup-container="triggerNode => triggerNode.parentNode">
                  <a-select-option v-for="item in dict.clientValues" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div>
          <form-fragment
            v-for="(formData, index) in apiDataExtends"
            :id="'form-' + index"
            :ref="handleSetFormRef"
            :key="index"
            v-model="apiDataExtends"
            :index="index"
            @delete="handleDeleteForm" />
          <!-- 允许添加的子表单数量等于需求类型的可选择数量 -->
          <a-button v-if="apiDataExtends.length < 4" type="link" size="small" @click="handleAddForm">
            <a-space>
              <e-icon type="add" />
              Add More
            </a-space>
          </a-button>
        </div>
      </a-spin>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button type="primary" @click="handleSave()">Save</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { reactive, ref, inject, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import FormFragment from './FormFragment.vue'
import { useQuoteApply } from '@/pages/Client/hooks/useQuoteApply.js'
import ServicePrice from '@/api/client/servicePrice.js'
import { useDict } from '@/hooks/useDict.js'
import Client from '@/api/client/index.js'
import TargetClient from '@/api/targetClient.js'
import { CHECK_FORM_INTEGRITY, CONFIRM_BACK_TO_DETAIL, UPLOAD_FAILED, APPLY_UPDATED } from '@/constants/message.js'
import { cloneDeep } from 'lodash-es'
const store = useStore()
const route = useRoute()
const router = useRouter()
const { Modal, message } = inject('Feedback')
const { isEditing } = inject('permissions')
const applyId = route.params.id
let clientId
const loading = ref(true)
const languagePairLoading = ref(true)
const bumSelectLoading = ref(true)
const backgroundInfoLoading = ref(true)
const gutter = [120, 16]
const dict = useDict()
const apiDataBase = reactive({
  theme: '',
  langPairID: [],
  bumid: undefined,
  attch: {
    attachmentAddr: '',
    attachmentFileSize: 0,
    attachmentName: ''
  }
})
const apiDataBackground = reactive({
  rivalID: 1,
  rivalLevelID: 1,
  valueID: 1
})
const apiDataExtends = reactive([])
const atomData = {
  aboutReviewID: 1,
  demandTypeID: '',
  demandContentID: [],
  notGoodID: 1,
  platformID: 1,
  proPOID: 1,
  processID: 1,
  purchaseModeID: 1,
  strategyID: 1,
  talkChannelID: 1,
  talkModeID: 1,
  useTranslationID: 1
}
apiDataExtends.push(cloneDeep(atomData))
const handleAddForm = () => {
  apiDataExtends.push(cloneDeep(atomData))
  nextTick(() => {
    window.location.hash = ''
    window.location.hash = 'form-' + (apiDataExtends.length - 1)
  })
}
const rules = {
  theme: [
    {
      required: true,
      whitespace: true,
      message: 'Please input Subject',
      trigger: 'blur'
    }
  ],
  langPairID: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least a pair of language',
      trigger: 'blur'
    }
  ],
  rivalID: [
    {
      type: 'number',
      required: true,
      message: 'Please select',
      trigger: 'blur'
    }
  ],
  rivalLevelID: [
    {
      type: 'number',
      required: true,
      message: 'Please select',
      trigger: 'blur'
    }
  ],
  valueID: [
    {
      type: 'number',
      required: true,
      message: 'Please select',
      trigger: 'blur'
    }
  ],
  bumid: [
    {
      type: 'number',
      required: true,
      message: 'Please select',
      trigger: 'blur'
    }
  ]
}
const formInstance = ref(null)
const backgroundFormInstance = ref(null)
const formFragmentInstances = ref(new Set())
const uploadInput = ref(null)
const fileName = ref('')
const uploadFileChange = event => {
  if (event.target.files.length > 0) {
    TargetClient.uploadFiles(event.target.files)
      .then(res => {
        if (Array.isArray(res) && res.length > 0 && res[0] instanceof Eci.IO.File) {
          fileName.value = event.target.files.length > 0 ? event.target.files[0].name : ''
          apiDataBase.attch.attachmentAddr = res[0].Path
          apiDataBase.attch.attachmentFileSize = res[0].SourceBaseFileSize
          apiDataBase.attch.attachmentName = fileName.value
          formInstance.value.clearValidate('fileName')
        } else {
          fileName.value = ''
          uploadInput.value.value = null
          message.error(UPLOAD_FAILED)
        }
      })
      .catch(() => {
        fileName.value = ''
        message.error(UPLOAD_FAILED)
      })
  }
}
const languagePairs = ref([])
const bumCandidates = ref([])
new Promise(resolve => {
  useQuoteApply(applyId, resolve)
}).then(({ raw }) => {
  clientId = raw.value.clientInfo.id
  ServicePrice.getLanguagePair(raw.value.clientInfo.id, raw.value.clientInfo.fromGrade)
    .then(({ data }) => {
      languagePairs.value = data
    })
    .finally(() => {
      languagePairLoading.value = false
    })
  ServicePrice.getBumCandidates(raw.value.clientInfo.id)
    .then(({ data }) => {
      bumCandidates.value = data
    })
    .finally(() => {
      bumSelectLoading.value = false
    })
  Client.getBackgroundInfo(raw.value.clientInfo.id).then(({ data }) => {
    backgroundInfoLoading.value = false
    if (data.cbg) {
      Object.keys(apiDataBackground).forEach(key => {
        apiDataBackground[key] = data.cbg[key]
      })
    }
    if (Array.isArray(data.cbgDemandType) && data.cbgDemandType.length > 0) {
      apiDataExtends.splice(0)
      data.cbgDemandType.forEach(demand => {
        apiDataExtends.push({
          demandTypeID: demand.demandTypeID,
          demandContentID: demand.demandContentID,
          proPOID: demand.proPOID,
          processID: demand.processID,
          purchaseModeID: demand.purchaseModeID,
          notGoodID: demand.notGoodID,
          talkChannelID: demand.talkChannelID,
          talkModeID: demand.talkModeID,
          aboutReviewID: demand.aboutReviewID,
          platformID: demand.platformID,
          useTranslationID: demand.useTranslationID,
          strategyID: demand.strategy,
          suggestedQuote: demand.suggestedQuote,
          decisionRoles: demand.decisionRoles
        })
      })
    }
  })
  loading.value = false
  apiDataBase.theme = raw.value.theme
  apiDataBase.langPairID = raw.value.langPair.map(langP => langP.langPairID)
  apiDataBase.bumid = raw.value.bumid
  apiDataBase.attch.attachmentName = raw.value.attchName
  apiDataBase.attch.attachmentAddr = raw.value.attchPath
  fileName.value = raw.value.attchName
})
const handleSetFormRef = ref => {
  if (ref && ref.formInstance) formFragmentInstances.value.add(ref.formInstance)
}
const handleDeleteForm = index => {
  apiDataExtends.splice(index, 1)
}
const emits = defineEmits(['updated'])
const handleSave = () => {
  const promises = []
  promises.push(formInstance.value.validate())
  promises.push(backgroundFormInstance.value.validate())
  formFragmentInstances.value.forEach(instance => {
    promises.push(instance.validate())
  })
  Promise.all(promises)
    .then(() => {
      ServicePrice.updateQuoteApply(applyId, apiDataBase).then(() => {
        Client.saveBackgroundInfo(applyId, clientId, apiDataBackground, apiDataExtends).then(() => {
          message.success(APPLY_UPDATED)
          emits('updated')
          router.push({ name: 'Price', params: { id: applyId } })
        })
      })
    })
    .catch(e => {
      console.log(e)
      message.error(CHECK_FORM_INTEGRITY)
    })
}
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      emits('updated')
      router.push({ name: 'Price', params: { id: applyId } })
    }
  })
}

store.dispatch('dict/getRivals')
store.dispatch('dict/getRivalLevels')
store.dispatch('dict/getClientValues')
store.dispatch('dict/getDemandTypes', { pid: 0, sub: false })
store.dispatch('dict/getForecastPOs')
store.dispatch('dict/getInternalLocalizationProcess')
store.dispatch('dict/getProcurementProcess')
store.dispatch('dict/getPainPoints')
store.dispatch('dict/getCommunicationChannels')
store.dispatch('dict/getCommunicationModes')
store.dispatch('dict/getReviewInfos')
store.dispatch('dict/getPlatforms')
store.dispatch('dict/getTranslationPurpose')
store.dispatch('dict/getQuotationStrategies')
</script>

<style lang="less" scoped>
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
</style>
<style lang="less">
.operation-logs {
  .ant-list-header {
    background-color: @milk;
    color: @text-gray;
    font-weight: bold;
  }
}
</style>
